package com.societyGames.flashForms
{
import flash.display.DisplayObject;
import flash.display.Sprite;

//Tries to take the whole width with each tile being equally wide.
public class HorizontalTileContainer extends Sprite
{
  protected var _desiredHeight:Number;
  protected var _desiredWidth:Number;
  protected var _items:Vector.<DisplayObject> = new Vector.<DisplayObject>();

  public function addItem(item:DisplayObject):void
  {
    var index:int = _items.indexOf(item);
    //If we don't already have it.
    if (index == -1)
    {
      //Add to the vector.
      _items.push(item);
      //Add to display list.
      this.addChild(item);
      //Recalculate graphics.
      calculate();
    }
  }

  public function removeItem(item:DisplayObject):void
  {
    var index:int = this._items.indexOf(item);
    if (index != -1)
    {
      this._items.splice(index, 1);
      this.removeChild(item);
      calculate();
    }
  }

  public function clearItems():void
  {
    for each (var item:DisplayObject in this._items)
    {
      this.removeChild(item);
    }
    this._items.length = 0;
  }

  public function get items():Vector.<DisplayObject>
  {
    return _items;
  }

  //Make all of the items in _items appear correctly.
  private function calculate():void
  {
    calculateWidth();
    calculateHeight();
  }

  protected function calculateWidth():void
  {
    var tileWidth:Number = this._desiredWidth / Number(this._items.length);
    var tileX:Number = 0;
    for each (var item:DisplayObject in this._items)
    {
      item.width = tileWidth;
      item.x = tileX;
      tileX += tileWidth;
      item.y = 0;
    }
  }

  protected function calculateHeight():void
  {
    for each (var item:DisplayObject in this._items)
    {
      item.height = this._desiredHeight;
    }
  }

  public override function set height(value:Number):void
  {
    if (value != this._desiredHeight)
    {
      this._desiredHeight = value;
      calculateHeight();
    }
  }

  //The width is pretty much ignored. Perhaps we should try to scale everything down equally to match the width?
  public override function set width(value:Number):void
  {
    if (value != this._desiredWidth)
    {
      this._desiredWidth = value;
      calculateWidth();
    }
  }
}
}